package com.example.springbootthreaddemo.demo03;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author: jixiaotian.ch@qq.com
 * @Date : 2020/8/28
 */
@RestController
public class InterruptDemo implements Runnable {
    private int i = 0;

    Thread t1;

    private boolean flag = true;

    private int number = 0;

    public boolean getFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        //Thread.currentThread().isInterrupted() = false
        while (!Thread.currentThread().isInterrupted()) {
            i++;
            System.out.println("Run Start:"+i);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                //e.printStackTrace();
                //再次中断
                System.out.println("flag:"+this.getFlag());
                if (!flag) {
                    System.out.println("终止");
                    Thread.currentThread().interrupt();
                } else {
                    System.out.println("打断一下");
                }

            }
            System.out.println("Run End:"+i);
        }
    }

    @GetMapping("/add")
    public int add(int x) {
        number += x;
        return  number;
    }

    @GetMapping("/subs")
    public int subs(int x) {
        number -= x;
        return  number;
    }

    @GetMapping("/start")
    public void start0() {
        t1 = new Thread(new InterruptDemo());
        t1.start();
    }
    @GetMapping("/interrupt")
    public void inter(boolean type) {
        this.setFlag(type);
        this.flag = type;
        t1.interrupt();
    }


}
